package cn.itcast.service.impl;

import cn.itcast.dao.AreaDao;
import cn.itcast.domain.Area;
import cn.itcast.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



import java.util.List;
@Service
@Transactional
public class AreaServiceImpl implements AreaService {
            @Autowired
        private AreaDao areaDao;
    @Override
    public void saveAll(List<Area> area) {
        areaDao.saveAll(area);
    }

    /**
     * 分页查询
     * @param page
     * @param rows
     * @return
     */
    @Override
    public Page<Area> pageQuery(Area area,int page, int rows) {
        //用exampleMatcher方法
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("province",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("city",ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("district",ExampleMatcher.GenericPropertyMatchers.contains());

        PageRequest pagResult = PageRequest.of(page-1, rows);
        Page<Area> result = areaDao.findAll(Example.of(area, matcher), pagResult);

        return  result;

        //根据查询条件,构造Specification条件查询对象
/*   Specification<Area> specification=new Specification<Area>() {
       @Override
       public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
           //将查询到的结果放到集合中
           List<Predicate> list = new ArrayList<Predicate>();

           //单表查询(查询当前对象对应的数据表),查询工号,等值查询
           if (StringUtils.isNotBlank(area.getProvince())) {
               Predicate p1 = criteriaBuilder.like(root.get("province").as(String.class),"%" +area.getProvince()+"%");
               list.add(p1);
           }
           if (StringUtils.isNotBlank(area.getCity())) {
               //查询所属单位,模糊查询
               Predicate p2 = criteriaBuilder.like(root.get("city").as(String.class), "%" + area.getCity() + "%");
               list.add(p2);
           }
           if (StringUtils.isNotBlank(area.getDistrict())) {
               //查询类型,等值查询
               Predicate p3 = criteriaBuilder.like(root.get("district").as(String.class),area.getDistrict());
               list.add(p3);
           }

           //new Predicate[0] 代表一个泛型,返回类型是Predicate
           return criteriaBuilder.and(list.toArray(new Predicate[0]));

       }
       };
        //调用Spring的方法
        PageRequest pageRequest = PageRequest.of(page - 1, rows);
        Page<Area> courierPage = areaDao.findAll(specification, pageRequest);
        return courierPage;*/
    }
}
